package com.example.library_room

import android.app.Application
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.library_room.dao.UserDao
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
object RoomModule {

    private const val databaseName = "my_app_db"

    @Provides
    @Singleton
    fun provideRoom(application: Application): AppDatabase =
        Room.databaseBuilder(application, AppDatabase::class.java, databaseName)
            //升级数据库
            //.addMigrations(MIGRATION_1_2)
            .build()

    //数据库变动添加，显示的影响版本1.0.0到1.0.1
    private val MIGRATION_1_2: Migration = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {
            //执行在库中加字段的SQL
            database.execSQL("ALTER TABLE chat_message_db ADD COLUMN order_json TEXT")
        }
    }

    @Provides
    @Singleton
    fun provideUserDao(appDatabase: AppDatabase): UserDao{
        return appDatabase.getUserDao()
    }
}